package cn.edu.zhku.citrusmonitor.law.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.tools.PDFText2HTML;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.edu.zhku.citrusmonitor.domain.Bean;
import cn.edu.zhku.citrusmonitor.domain.Law;
import cn.edu.zhku.citrusmonitor.law.service.LawService;
import cn.edu.zhku.citrusmonitor.law.service.LawServiceImpl;
import cn.edu.zhku.citrusmonitor.law.util.PageBean;
import cn.edu.zhku.citrusmonitor.util.BaseServlet;
import cn.edu.zhku.citrusmonitor.util.DirectoryBrokenUtil;
import cn.edu.zhku.citrusmonitor.util.Message;

@WebServlet("/law.do")
public class LawServlet extends BaseServlet{
	LawService ls=new LawServiceImpl();
	/**
	 * 添加法规
	 * @param request
	 * @param response
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public String add(HttpServletRequest request,HttpServletResponse response) throws IllegalAccessException, InvocationTargetException, FileUploadException, IOException {
		
		Law law=new Law();
		DiskFileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload sfu=new ServletFileUpload(factory);
		Map<String,List<String>> m=new HashMap<String,List<String>>();
		if(sfu.isMultipartContent(request)) {
			List<FileItem> items=sfu.parseRequest(request);
			for(FileItem item:items) {
				if(item.isFormField()) {
					//普通表单项	
					//判断是否为复选框
					if(m.get(item.getFieldName())!=null) {
						m.get(item.getFieldName()).add(item.getString("UTF-8"));
					}else {
						List<String> l=new ArrayList<String>();
						l.add(item.getString("UTF-8"));
						m.put(item.getFieldName(),l);
					}
						
				}else {
					//上传表单项
					InputStream is=item.getInputStream();
					String formFilePath=item.getName();
					String fileName=formFilePath.substring(formFilePath.lastIndexOf(File.separator)+1);
					
					String sysPath=request.getServletContext().getRealPath("/");//获取当前应用后文件路径					
					System.out.println("syspath="+sysPath);
					File sysFile=new File(sysPath+"upload\\law\\");
					System.out.println(sysFile);
					String childPath=DirectoryBrokenUtil.directoryBrokenByDate(sysFile, fileName);
					//文件存储路径
					
					File realFile=new File(sysPath+"upload\\law\\"+childPath,fileName);
					
					System.out.println("realfile:"+realFile);
					FileOutputStream out=new FileOutputStream(realFile);
					byte[] b=new byte[1024];
					int len;
					while((len=is.read(b))!=-1) {
						out.write(b, 0, len);
					}
					item.delete();
					is.close();
					out.close();
					List<String> l=new ArrayList<String>();
					l.add("upload/law/"+childPath+"/"+fileName);
					m.put(item.getFieldName(),l);
				}
					
				
			}
			BeanUtils.populate(law, m);
			law.setLawId(UUID.randomUUID().toString());
			//pdf文档解析
			PDDocument pdfdoc=new PDDocument();
			String sysPath=request.getServletContext().getRealPath(law.getFilePath());
			File file=new File(sysPath);
			pdfdoc=PDDocument.load(file);
			//PDFTextStripper textStripper=new PDFTextStripper();
			//textStripper.getText(pdfdoc);
			//转为html格式并存入数据库
			PDFText2HTML pt2h=new PDFText2HTML();
			
			System.out.println();
			law.setContent(pt2h.getText(pdfdoc));
			pdfdoc.close();
			pt2h.endDocument(pdfdoc);
			//System.out.println("content"+law.getContent());
			String path=law.getFilePath();
			String fileName=path.substring(path.lastIndexOf("/")+1,path.lastIndexOf("."));
			
			if(law.getTittle()==null||law.getTittle().trim().equals(""))				
				law.setTittle(fileName);
			
			if(ls.addLaw(law).equals("success")) {
				System.out.println(JSON.toJSONString(new Message("1","添加成功")));
				return JSON.toJSONString(new Message("1","添加成功"));
			}else
				return JSON.toJSONString(new Message("2","添加失败"));
			
		}else
			return JSON.toJSONString(new Message("2","上传表单enctype类型不是\"multipart/form-data\"类型"));
		
		
	}
	/**
	 * 通过标题查找法规(模糊查询)
	 * @param request
	 * @param response
	 * @return
	 */
	public String findLawByTittle(HttpServletRequest request,HttpServletResponse response) {
		String tittle=request.getParameter("tittle");
		List<Law> list=new ArrayList<Law>();
		if((list=ls.findLawByTittle(tittle))!=null) {
			System.out.println(JSON.toJSONString(list));
			return JSON.toJSONString(list);
			
		}else
			return JSON.toJSONString(new Message("2","查找失败"));
	}
	/**
	 * 分页查找
	 * @param request
	 * @param response
	 * @return
	 */
	public String show(HttpServletRequest request,HttpServletResponse response) {
		PageBean<Law> lawPage=new PageBean<Law>();
		int currentPage=lawPage.getCurrentPage(); //默认第一页
		if(request.getParameter("currentPage")!=null) {
			currentPage=Integer.parseInt(request.getParameter("currentPage"));
		}
		int pageSize=lawPage.getPageSize();
		if(request.getParameter("pageSize")!=null) {
			pageSize=Integer.parseInt(request.getParameter("pageSize"));
		}
		
		long total=ls.getTotalCounts();
		List<Law> list=ls.getBeanList(currentPage,pageSize);
		if(total!=0&&list!=null) {
			lawPage.setList(list);
			lawPage.setCount(total);
			lawPage.setCurrentPage(currentPage);
			lawPage.setPageSize(pageSize);
//			System.out.println(JSON.toJSONString(lawPage));
			return JSON.toJSONString(lawPage);
		}else
			return JSON.toJSONString(new Message("2","查找失败"));
	}
	/**
	 * 部分展示查找
	 */
	public String showPartly(HttpServletRequest request,HttpServletResponse response) {
		
		String pageSize=request.getParameter("pageSize");
		List<Law> list=new ArrayList<Law>();
		if((list=ls.getBeanList(pageSize))!=null) {
			//System.out.println(JSON.toJSONString(list));
			return JSON.toJSONStringWithDateFormat(list, "yyyy-MM-dd", SerializerFeature.EMPTY);
		}else 
			return JSON.toJSONString(new Message("2","查找失败"));
		
	}
	
	/**
	 * 通过id查找
	 * @param request
	 * @param response
	 * @return
	 */
	public String findById(HttpServletRequest request,HttpServletResponse response) {
		String id=request.getParameter("lawId");
		Law oldLaw;
		if((oldLaw=ls.findLawById(id))!=null) {
			
			System.out.println(oldLaw.getLawId()+oldLaw.getFilePath());
			return JSON.toJSONStringWithDateFormat(oldLaw, "yyyy-MM-dd", SerializerFeature.EMPTY);
		}else
			return JSON.toJSONString(new Message("2","查找失败"));
			
	}
	/**
	 * 通过id修改
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException 
	 * @throws FileUploadException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public String modify(HttpServletRequest request,HttpServletResponse response) throws IOException, FileUploadException, IllegalAccessException, InvocationTargetException {

		Law law=new Law();
		DiskFileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload sfu=new ServletFileUpload(factory);
		Map<String,List<String>> m=new HashMap<String,List<String>>();
		if(sfu.isMultipartContent(request)) {
			List<FileItem> items=sfu.parseRequest(request);
			for(FileItem item:items) {
				if(item.isFormField()) {
					//普通表单项	
					//判断是否为复选框
					if(m.get(item.getFieldName())!=null) {
						m.get(item.getFieldName()).add(item.getString("UTF-8"));
					}else {
						List<String> l=new ArrayList<String>();
						l.add(item.getString("UTF-8"));
						m.put(item.getFieldName(),l);
					}
						
				}else {
					//上传表单项
					InputStream is=item.getInputStream();
					String formFilePath=item.getName();
					String fileName=formFilePath.substring(formFilePath.lastIndexOf(File.separator)+1);
					
					String sysPath=request.getServletContext().getRealPath("/");
					System.out.println("syspath="+sysPath);
					File sysFile=new File(sysPath+"upload\\law");
					
					String childPath=DirectoryBrokenUtil.directoryBrokenByDate(sysFile, fileName);
					//文件存储路径
					File realFile=new File(sysPath+"upload\\law\\"+childPath,fileName);
					System.out.println("realfile:"+realFile);
					FileOutputStream out=new FileOutputStream(realFile);
					byte[] b=new byte[1024];
					int len;
					while((len=is.read(b))!=-1) {
						out.write(b, 0, len);
					}
					item.delete();
					
					out.close();
					is.close();
					List<String> l=new ArrayList<String>();
					l.add("upload/law/"+childPath+"/"+fileName);
					m.put(item.getFieldName(),l);
				}
					
				
			}
			BeanUtils.populate(law, m);
			
			//pdf文档解析
			PDDocument pdfdoc=new PDDocument();
			
			String sysPath=request.getServletContext().getRealPath(law.getFilePath());
			File file=new File(sysPath);
			
			
			
			pdfdoc=PDDocument.load(file);
			//PDFTextStripper textStripper=new PDFTextStripper();
			//textStripper.getText(pdfdoc);
			//转为html格式并存入数据库
			PDFText2HTML pt2h=new PDFText2HTML();
			law.setContent(pt2h.getText(pdfdoc));
			pdfdoc.close();
			//System.out.println("content"+law.getContent());
			
			
			
			//System.out.println(law.getLawId()+law.getFilePath());
			if(ls.modifyLaw(law).equals("success")) {
				System.out.println(JSON.toJSONString(new Message("1","修改成功")));
				return JSON.toJSONString(new Message("1","修改成功"));
			}else
				return JSON.toJSONString(new Message("2","修改失败"));
		
		}else
			return JSON.toJSONString(new Message("2","表单格式不正确"));
	}
	
	public String download(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String id=request.getParameter("lawId");
		Law oldLaw;
		if((oldLaw=ls.findLawById(id))!=null) {			
		
		String filename=oldLaw.getFilePath().substring(oldLaw.getFilePath().lastIndexOf("/")+1);
		System.out.println(filename);
		//解决文件名乱码
		if(request.getHeader("user-agent").toLowerCase().contains("msie")) {
			filename=URLEncoder.encode(filename,"UTF-8");
		}else//针对火狐浏览器
			filename=new String(filename.getBytes("UTF-8"),"iso8859-1");
		response.setHeader("content-disposition", "attachment;filename="+filename);
		response.setContentType(request.getServletContext().getMimeType(filename));
		System.out.println("type="+request.getServletContext().getMimeType(filename));
		
		//获取文件路径：/upload/balabla/adasd.pdf
		File file=new File(request.getServletContext().getRealPath(oldLaw.getFilePath()));
		
		System.out.println(file);
		FileInputStream fis=new FileInputStream(file);
		//InputStreamReader reader=new InputStreamReader(fis);
		
		//PrintWriter out=response.getWriter();
		ServletOutputStream out=response.getOutputStream();
		byte[] b=new byte[1024];
		int len;
		while((len=fis.read(b))!=-1) {
			out.write(b,0,len);
		}
		out.close();
		fis.close();
			return JSON.toJSONString(new Message("1","下载成功"));
		}else
			return JSON.toJSONString(new Message("2","下载失败"));
	}
	/**
	 * 前端分页数据封装
	 * @param request
	 * @param response
	 * @return
	 */
	public String frontLaw(HttpServletRequest request,HttpServletResponse response) {
		PageBean<Bean> page=new PageBean<Bean>();
		String currentPage=request.getParameter("currentPage");
		String pageSize=request.getParameter("pageSize");
		if(currentPage!=null&&!currentPage.equals("")) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if(pageSize!=null&&!pageSize.equals("")) {
			page.setPageSize(Integer.parseInt(pageSize));
		}
		page.setCount(ls.getWebCounts());
		page.setList(ls.getWebList(page.getCurrentPage(),page.getPageSize()));
		if(page.getList()!=null&&page.getCount()!=null) {
			System.out.println(page.getList().size());
			return JSON.toJSONStringWithDateFormat(page, "yyyy-MM-dd", SerializerFeature.EMPTY);
		}else
			return JSON.toJSONString(new Message("2","查找失败"));

		
	}
	/**
	 * 前端具体某一条数据封装（根据id）
	 * @param request
	 * @param response
	 * @return
	 */
	public String detail(HttpServletRequest request,HttpServletResponse response) {
		String id=request.getParameter("id");
		Bean b=new Bean();
		if((b=ls.selectOne(id))!=null) {
			return JSON.toJSONStringWithDateFormat(b, "yyyy-MM-dd", SerializerFeature.EMPTY);
		}else
			return JSON.toJSONString(new Message("2","查找失败"));		
	}
	

	/**
	 * 根据id删除
	 * @param request
	 * @param response
	 * @return
	 */

	public String delete(HttpServletRequest request,HttpServletResponse response) {
		String id=request.getParameter("lawId");
		if(ls.deleteLaw(id)!=0) {
			return JSON.toJSONString(new Message("1","删除成功"));
		}else
			return JSON.toJSONString(new Message("2","删除失败"));
	}
	/**
	 * 批量删除byid
	 * @param request
	 * @param reponse
	 * @return
	 */
	public String removeAll(HttpServletRequest request,HttpServletResponse reponse) {
		String id=request.getParameter("ids");
		String[] ids=id.split(",");
		if(ids.length==0||ids==null) {
			return JSON.toJSONString(new Message("2","获取id失败"));
		}
		if(ids.length==ls.removeAll(ids)) {
			return JSON.toJSONString(new Message("1","批量删除成功"));
		}
		return JSON.toJSONString(new Message("2","批量删除失败"));
		
		
		
	}
}
	

